'use strict'

import axios from 'axios'

import { tasilyEncode, aesDecrypt, getSymmKey, getSymmKeyIndex } from '../libs/util'
const notLogin = '用户未登录'

export default {
  /**
   *加密接口请求
   *
   * @param {*} data
   * @param {*} url
   * @param {*} success
   * @param {*} fail
   * @param {*} [method = 'POST']
   */
  commToServer (data, url, success, fail, method = 'POST') {
    let symmKey = getSymmKey()
    let symmkeyIndex = getSymmKeyIndex()
    if (!symmKey || !symmkeyIndex) {
      // window.alert(notLogin)
      console.debug(notLogin, '=====================')
    }
    this.tasilyAjax(tasilyEncode(data, symmkeyIndex, symmKey), url, result => {
      if (result.status && result.status === 'notLogin') {
        if (fail) fail('notLogin')
        return
      }
      if (success && typeof success === 'function') {
        if (result.status === 'error') {
          window.alert(result.info)
          if (fail) fail(result.info)
        } else {
          success(aesDecrypt(result.data, symmKey))
        }
      }
    }, error => {
      if (fail && typeof fail === 'function') fail(error)
    }, method)
  },
  /**
   * 页面接口请求
   * @param {请求接口参数} data
   * @param {请求的接口} url
   * @param {成功的回调} success
   * @param {报错的回调} fail
   * @param {请求接口的类型(post || get)} method
   */
  tasilyAjax (data, url, success, fail, method = 'POST') {
    if (process.env.NODE_ENV !== 'production') url = '/api/' + url
    data = typeof (data) === 'object' ? window.JSON.stringify(data) : data
    axios({
      method: method,
      url: url,
      dataType: 'json',
      //   contentType: 'application/json; charset=utf-8',
      data: data,
      // timeout: 5000,
      headers: {
        'Content-Type': 'application/json'
        // 'X-Requested-With': 'XMLHttpRequest',
        // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then((response) => {
      success(response.data)
    }).catch(function (error) {
      fail(error)
      console.debug('error:', error)
    })
  }
}
